import { Injectable, Req, ExecutionContext } from '@nestjs/common';
import { InjectEntityManager, InjectRepository } from '@nestjs/typeorm';
import { Like, Repository, EntityManager } from 'typeorm';
import { instanceToPlain, plainToInstance } from 'class-transformer';
import { genSalt } from 'bcryptjs';

import { CustomerEntity } from './entities/customer.entity';

import { ResultData } from '../common/utils/result';
import { AppHttpCode } from '../common/enums/code.enum';

import { CreateCustomerDto } from './dto/create-customer.dto';
import { UpdateCustomerDto } from './dto/update-customer.dto';
import { FindCustomerListDto } from './dto/find-customer-list.dto';

import { OperalogService } from 'src/system/operalog/operalog.service';

@Injectable()
export class CustomerService {
  constructor(
    @InjectRepository(CustomerEntity)
    private readonly customerRepo: Repository<CustomerEntity>,
    @InjectEntityManager()
    private readonly customerManager: EntityManager,
    private readonly operalogService: OperalogService,
  ) {}

  async findOneById(id: string): Promise<CustomerEntity> {
    let customer = await this.customerRepo.findOne({ where: { id } })
    customer = plainToInstance(CustomerEntity, { ...customer }, { enableImplicitConversion: true })
    return customer
  }

  /** 创建客户 */
  async create(createCustomerDto: CreateCustomerDto, account: String, ip: String) {
    // 防止重复创建
    const salt = await genSalt()
    const customer = plainToInstance(CustomerEntity, { salt, ...createCustomerDto }, { ignoreDecorators: true })
    const result = await this.customerManager.transaction(async (transactionalEntityManager) => {
      return await transactionalEntityManager.save<CustomerEntity>(customer)
    })

    if (!result) ResultData.fail(AppHttpCode.SERVICE_ERROR, '创建失败，请稍后重试');

    /** 创建客户成功后插入操作日志 */
    if (ip.indexOf('::ffff:') !== -1) {
      ip = ip.substring(7)
    }
    this.operalogService.create({
      systemMenu: '客户',
      operaModule: `添加客户 -【${createCustomerDto.name}】`,
      operaName: account,
      operaIp: ip,
      status: 1
    })
    return ResultData.ok(instanceToPlain(result));
  }

  /** 查询客户分页查询 */
  async findList(dto: FindCustomerListDto) {
    const { page, size, name, phone } = dto;
    const where = {
      ...(name ? { name: Like(`%${name}%`) } : null),
      ...(phone ? { phone: Like(`%${phone}%`) } : null),
      isDelete: 1
    }
    const customer = await this.customerRepo.findAndCount({
      where,
      order: { id: 'DESC' },
      skip: size * (page - 1),
      take: size,
    })
    return ResultData.ok({ list: instanceToPlain(customer[0]), total: customer[1] })
  }

  /** 查询客户信息 */
  async findOne(id: string) {
    const customer = await this.findOneById(id)
    if (!customer) return ResultData.fail(AppHttpCode.USER_NOT_FOUND, '该客户不存在或已删除')
    return ResultData.ok(instanceToPlain(customer))
  }

  /** 更新客户 */
  async update(updateCustomerDto: UpdateCustomerDto, account: String, ip: String) {
    /** 查询当前伙伴是否存在 */
    const existing = await this.findOneById(updateCustomerDto.id)
    if (!existing) return ResultData.fail(AppHttpCode.USER_NOT_FOUND, '该客户不存在或已删除');
    /** 更新客户 */
    const customerInfo = instanceToPlain(updateCustomerDto)
    const { affected } = await this.customerManager.transaction(async (transactionalEntityManager) => {
      return await transactionalEntityManager.update<CustomerEntity>(CustomerEntity, updateCustomerDto.id, customerInfo)
    })

    if (!affected) ResultData.fail(AppHttpCode.SERVICE_ERROR, '更新失败，请稍后重试');
    /** 更新客户成功后插入操作日志 */
    if (ip.indexOf('::ffff:') !== -1) {
      ip = ip.substring(7)
    }
    this.operalogService.create({
      systemMenu: '客户',
      operaModule: `更新客户 -【${updateCustomerDto.name}】`,
      operaName: account,
      operaIp: ip,
      status: 1
    })
    return ResultData.ok();
  }

  /** 逻辑删除客户 */
  async updateDelete(customerId: string, isDelete: 0 | 1, account: String, ip: String): Promise<ResultData> {
    /** 查询当前伙伴是否存在 */
    const existing = await this.findOneById(customerId)
    if (!existing) ResultData.fail(AppHttpCode.USER_NOT_FOUND, '当前客户不存在或已删除')
    /** 逻辑删除客户 */
    const { affected } = await this.customerManager.transaction(async (transactionalEntityManager) => {
      return await transactionalEntityManager.update<CustomerEntity>(CustomerEntity, customerId, { id: customerId, isDelete })
    })
    if (!affected) ResultData.fail(AppHttpCode.SERVICE_ERROR, '删除失败，请稍后尝试');

    /** 逻辑删除客户成功后插入操作日志 */
    if (ip.indexOf('::ffff:') !== -1) {
      ip = ip.substring(7)
    }
    this.operalogService.create({
      systemMenu: '客户',
      operaModule: `删除客户 -【${existing.name}】`,
      operaName: account,
      operaIp: ip,
      status: 1
    })
    return ResultData.ok()
  }
}
